# 包装目的可以包装标准类型、可以对已有的做包装定制
'''
    __getatter__ 、__delattr__、__setattr__、__getattribute__
    在调用的属相不存在的情况下会触发该函数执行
'''
class Foo:
    def __init__(self,name):
        self.name =name
    # __getattr__找不到属性时开始执行、即授权
    def __getattr__(self, item):
        print("你找的【%s】属性不存在" % item)

    # def __getattribute__(self, item):
    #     print("不管属性有没有都会执行 __getattribute__")
    #     raise AssertionError("抛出异常了")
    # __getattribute__抛出AssertionError异常后执行__getattr__

    def __setattr__(self, key, value):
        print("执行setattr",key,value)
        if type(value) is str:
            print("开始设置")
            self.__dict__[key]=value.upper()
        else:
            print("必须为字符串")
    def __delattr__(self, item):
        print("执行delatter",item)
        self.__dict__.pop(item)
class Bar(Foo):
    pass

f1=Foo("alex")
print("删除之前",f1.__dict__)
f1.age=18
f1.gendle ="女"
f1.salary=7000
print("----------------------------")

del f1.name
print("删除之后",f1.__dict__)
print(f1.age)
print(f1.gendle)
print(f1.salary)
print("_____________________________")
b1=Bar('yuhao')
print(isinstance(b1,Bar))
print(isinstance(b1,Foo))
# # ----------------------------------
class List(list):
    def append(self, object):
        if type(object) is str:
            # list.append(self,object)
            super().append(object)
        else:
            print("必须为字符串")
    def shouMidler(self):
        midIndex = int(len(self)/2)
        return self[midIndex]
l1=List("HelloWorld")
print("输出的中间值为",l1.shouMidler())
l1.append(65655757)
print(l1)
l1.append("sb")
print(l1)

# ------__getitem__、__setitem__、__delitem__ 只适用字典的方式----------------------------
print("_________________ffff____________________________")
class ffff:
    def __getitem__(self, item):
        print("你找的【%s】属性" %item)
        return self.__dict__[item]

    # def __getattribute__(self, item):
    #     print("不管属性有没有都会执行 __getattribute__")
    #     raise AssertionError("抛出异常了")

    # __getattribute__抛出AssertionError异常后执行__getattr__

    def __setitem__(self, key, value):
        print("执行__setitem__",key,value)
        if type(value) is str:
            print("开始设置")
            self.__dict__[key]=value.upper() # 定制设置属性
        else:
            print("必须为字符串")
    def __delitem__(self, item):
        print("执行__delitem__",item)
        self.__dict__.pop(item) # 定制删除属性

tt=ffff()
print(tt.__dict__)
tt["name"]="alex11"
tt['gendler']="女"
tt['age']="18"
print(tt.__dict__)

print("-----------------删除之后---------")
del tt.name  # 触发的是__delattr__ 、而不是__delitem__
print(tt.__dict__)
print("_________________z字典方式删除——————————————————————")
# del tt['name']
print(tt.__dict__)
tt['name']
tt['gendler']
